<?php
namespace Api\Controller;
use Api\Controller\CommonController;
class UserController extends CommonController {
    public function _initialize(){
    	parent::_initialize();
    	
    	//登录验证
    	$this->_checkLogin();
    }
	
	
	public function getHuitongToken(){
		S(C("CACHE_MEM"));
		$userID = $this->user['uid'];
		$user = D("User")->getUser("","",$userID);
		if(S("huitongtoken_".$userID) && S("huitongtoken_".$userID)==$user['token']){
			$this->_returnJson(array("result"=>1,"huitongToken"=>S("huitongtoken_".$userID)));
		} else {
			
			$result=$this->_loginPassword($user['phone'],$user['password']);
			if (!$result) {
				$this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
			}
			S("huitongtoken_".$userID, $result['token'], 60*60*24);
			D("User")->save(
		      array(
		          "userID"=>$userID,
		          "token"=>$result['token']
		      )
			);
			$this->_returnJson(array("result"=>1,"huitongToken"=>$result['token']));
			
		}
		
		
		
	}
	
	/**
	 *  用户个人信息 
	 */
	public function info(){
		$info=$this->_checkAccount();
    	
    	$return=array(
    		"mobileNum"=>$info['phone'],
    		"nickName"=>$info['nickName'],
    		"headImg"=>C('IMG_DOMAIN').$info['headImg'],
    		"carNum"=>$info['carNum'],
    		"carBrand"=>$info['carBrand'],
    		"carType"=>$info['carType'],
    		"carMenName"=>$info['carMenName'],
    		"idcard"=>$info['idcard'],
    		"sex"=>$info['sex']	
    	);
    	
    	$this->_returnJson(array("result"=>1,"info"=>$return));
    }
    
    /**
     *  修改用户个人信息
     */
    public function editInfo(){
    	$info=$this->_checkAccount();
    	
    	isset($_POST['nickName'])?$data['nickName']=I("post.nickName"):"";
    	isset($_POST['headImg'])?$data['headImg']=I("post.headImg"):"";
    	isset($_POST['carNum'])?$data['carNum']=I("post.carNum"):"";
    	isset($_POST['carType'])?$data['carType']=I("post.carType"):"";
    	isset($_POST['carBrand'])?$data['carBrand']=I("post.carBrand"):"";
    	isset($_POST['idcard'])?$data['idcard']=I("post.idcard"):"";
    	isset($_POST['carMenName'])?$data['carMenName']=I("post.carMenName"):"";
    	isset($_POST['sex'])&&in_array($_POST['sex'], array("0","1"))?$data['sex']=I("post.sex"):"";
    	
    	$data['updateTime']=time();
    	$data['userID']=$info['userID'];
    	
    	$result=D("User")->updateUser($data);
    	
    	if (!$result) {
    		$this->_returnJson(array("result"=>0,"info"=>"update fail","code"=>121));
    	}
    	
    	$this->_returnJson(array("result"=>1));
    }
    
    /**
     *  我的汇通卡
     */
    public function myCard(){
    	$info=$this->_checkAccount();
    	
    	
    }
    
    /**
     *  上传用户头像
     */
    public function uploadImg(){
    	$info=$this->_checkAccount();
    	
    	/* $rsp = "{}";
    	$dir = "./Public/user/headImg/".$info['phone']."/";
    	$f = true;
    	
    	if (file_exists($dir) == false) {//创建图片目录
    		if (mkdir($dir, 0777, true) == false) {
    			$f = false;
    		} else if (chmod($dir, 0777) == false) {
    			$f = false;
    		}
    	}
    	
    	if ($f) {
    		$tm = time();
    		$path = $dir . $tm . substr(str_shuffle('0123456789abcdefg'), 0, 3) . ".jpg";
    		
    		if (file_put_contents($path, base64_decode($_REQUEST['file'])) > 0) {
    			$this->_returnJson(array("result"=>1,"path"=>ltrim($path,".")));
    		} 
    		else {
    			$this->_returnJson(array("result"=>0,"info"=>"upload error","code"=>120));
    		}
    	}
    	else{
    		$this->_returnJson(array("result"=>0,"info"=>"upload error","code"=>120));
    	} */
    	//dump($_POST['file']);
    	$data=array(
    		'file'=>$_POST['file'],
    		'type'=>'bit',
    		'savePath'=>'Public/user/headImg/'
    	);
    	
    	$rt=http_post(C('IMG_UPLOAD_URL').'/upload.php?sign='.C('IMG_SIGN'), $data,true);
    	if ($rt){
    		$rt=json_decode($rt,true);
    		
    		if($rt['result']){
    			$this->_returnJson(array("result"=>1,"path"=>$rt['path']));
    		}
    	}
    	
    	$this->_returnJson(array("result"=>0,"info"=>"upload error",'errorMsg'=>$rt['errorMsg'],"code"=>120));
    	
    	
    	
    	
    }
    
    /**
     *  订单详情
     */
    public function orderDetail(){
    	$data=array(
    			"orderSn"=>I("orderSn"),
    	);
    	if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    	//判断订单是否存在
    	$order=D("Order")->getOrder("",array("orderSn"=>$data['orderSn'],"userID"=>$this->user['uid'],"isOn"=>1));
    	if(!$order) $this->_returnJson(array("result"=>0,"info"=>"order is not exist","code"=>"133"));
    	
    	//获取订单商品
    	$orderGoods=D("OrderGoods")
    	->field("goodsID,goodsName,shopID,goodsPrice,num,comtPrice,unit,phone")
    	->where(array("orderID"=>$order['orderID']))
    	->select();
    	
    	$shopIDs=array();
    	foreach ($orderGoods as $a){
    		if(!in_array($a,$shopIDs)) $shopIDs[]=$a['shopID'];
    	}
    	 
    	//获取商店
    	$shop=D("Shop")
    	->field("shopID,shopName")
    	->where(array("shopID"=>array("in",implode(",", $shopIDs))))
    	->select();
    	
    	if($order['orderType']==1){
    	    //获取消费卷
    	    $orderCode=D("OrderCode")
    	    ->field("goodsID,assisCode,endTime,mobile,parPrice")
    	    ->where(array("orderID"=>$order['orderID']))
    	    ->select();
    	}
    	
    	
    	
    	
    	foreach ($shop as $key=>$a){
    		foreach($orderGoods as $key2=>$b){
    			if ($a['shopID']==$b['shopID']) {
    				$shop[$key]['goods'][]=$b;
    				unset($orderGoods[$key2]);
    			}
    		}
    	}
    	
    	if($order['orderType']==1){
    	    foreach ($shop as $key=>$a){
    	        foreach ($a['goods'] as $key2=>$b){
    	            foreach ($orderCode as $key3=>$c){
    	                if ($c['goodsID']==$b['goodsID']) {
    	                    $shop[$key]['goods'][$key2]['qrcode'][]=$c;
    	                    unset($orderCode[$key3]);
    	                }
    	            }
    	        }
    	    } 
    	}
    	
    	
    	
    	
    	$return=array(
    			"order"=>array(
    				"orderSn"=>$order['orderSn'],
    				"payPrice"=>$order['payPrice'],
    				"status"=>$order['status'],
    			    "logisticsStatus"=>$order['logisticsStatus'],
    			    "logisticsNo"=>$order['logisticsNo'],
    				"payModeID"=>$order['payModeID'],
    				"payModeName"=>$order['payModeName'],
    				"orderTime"=>$order['addTime'],
    			    "orderType"=>$order['orderType'],
    			),
    			"info"=>$shop
    	);
    	
    	$this->_returnJson(array("result"=>1,"info"=>$return));
    }
    
    /**
     *  订单列表
     */
    public function orderList(){
        
    	empty($_POST['page'])?$page=1:$page=intval(I("post.page"));
    	empty($_POST['pageSize'])?$pageSize=15:$pageSize=intval(I("post.pageSize"));
    	
    	$where=array(
    			"isOn"=>1,
    			"userID"=>$this->user['uid']
    	);
    	
    	switch (I("post.status")){
			case "noPay" :	//未付款
				$where['status']=0;
				break;
			case "paid" :  //已付款
				$where['status']=1;
				break;
			case "finish" : //已完成
			    $where['status']=2;
			    break;
		    case "cancel" : //已完成
		        $where['status']=3;
		        break;
			default:
				break;
		}
    	
    	$order=array(
    			"orderID"=>"desc"
    	);
    	
    	$count=D("Order")->where($where)->count();
    	/* $pp=$count/$pageSize;
    	if($pp == 0) $pageCount=1;
    	else if ($count % $pageSize!=0)  $pageCount=intval($pp)+1;
    	else $pageCount=$pp;
    	
    	if ($pageCount < $page) $this->_returnJson(array("result"=>0,"info"=>"page too big","code"=>"114"));
    	 */
    	$pageInfo=$this->paging($count, $page, $pageSize);
    	//获取订单列表
    	$list=D('order')->where($where)->order($order)->page($page,$pageSize)->select();
    	
    	if (!$list){
    		$this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"139"));
    	}
    	
    	foreach ($list as $a){
    		$orderIDs[]=$a['orderID'];
    		$return[]=array(
    			"orderID"=>$a['orderID'],
    			"orderSn"=>$a['orderSn'],
    			"payPrice"=>$a['payPrice'],
    		    "orderType"=>$a['orderType'],
    			"status"=>$a['status'],
    		    "logisticsStatus"=>$a['logisticsStatus'],
    		    "logisticsNo"=>$a['logisticsNo'],
    			"addTime"=>$a["addTime"]
    		);
    	}
    	
    	//获取订单商品
    	$orderGoods=D("OrderGoods")
    	->field("goodsID,goodsName,shopID,orderID,orderSn,num,goodsPrice,comtPrice,unit")
    	->where(array("orderID"=>array("in",implode(",", $orderIDs))))
    	->select();
		
    	$shopIDs=array();
    	foreach ($orderGoods as $a){
    		if(!in_array($a,$shopIDs)) $shopIDs[]=$a['shopID'];
    	}
    	
    	//获取商店
    	$shop=D("Shop")
    	->field("shopID,shopName")
    	->where(array("shopID"=>array("in",implode(",", $shopIDs))))
    	->select();
    	
    	//组装数据
    	foreach ($return as $key=>$a){
    		foreach ($orderGoods as $key2=>$b){
    			if ($a['orderID']==$b['orderID']) {
    				$return[$key]['goods'][$b['shopID']][]=$b;
    				unset($orderGoods[$key2]);
    			}
    		}
    	}
    	
    	foreach ($return as $key=>$a){
    		foreach ($a['goods'] as $key2=>$b){
    			foreach ($shop as $key3=>$c){
    				if ($c['shopID']==$key2) {
    					$return[$key]['shop'][]=array(
    						"info"=>$c,
    						"goods"=>$b
    					);
    				}
    			}
    		}
    		unset($return[$key]['goods']);
    	}
    	
    	//dump($return);
    	//dump($shop);
    	
    	//dump($orderGoods);
    	
    	$this->_returnJson(array("result"=>1,"list"=>$return,"page"=>$pageInfo/* array("page"=>$page,"pageSize"=>$pageSize,"pageCount"=>$pageCount,"count"=>$count) */));
    }
    
    /**
     *  二维码列表
     */
    public function barCodeList(){
		$pageSize = intval(I("post.pageSize"));
		$page = intval(I("post.page"));
        empty($pageSize)?$pageSize=15:$pageSize=intval(I("post.pageSize"));
        empty($page)?$pageIndex=1:$pageIndex=intval(I("post.page"));
        
        $info=$this->_checkAccount();
        //dump($info);exit;
        $result=$this->_queryBarCodeList(/* "02",
            $this->user['mobileNum'],
            $info['password'],
            $info['token'], */
            $this->user['mobileNum'],
			//'13902409658',
            $pageSize,$pageIndex);
        //dump($result);
        if(!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119"));
        $this->_returnJson(array("result"=>1,"info"=>$result));
    }
    
    /**
     *  二维码详细
     */
    public function barCodeDetail(){
		$assisCode = I("post.assisCode");
        empty($assisCode)?$this->_returnJson(array("result"=>0,"info"=>"empty assisCode","errorMsg"=>$this->apiErrorMsg,"code"=>"135")):$assisCode=I("post.assisCode");
        $result=$this->_queryBarCodeDetail($assisCode,/* "02", */$this->user['mobileNum']/* ,"e10adc3949ba59abbe56e057f20f883e" */);
        //dump($result);
        if(!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119"));
        $this->_returnJson(array("result"=>1,"info"=>$result));
    }
    
    /**
     *  用户地址列表
     */
    public function addressList(){
		$pageSize = intval(I("post.pageSize"));
		$page = intval(I("post.page"));
        empty($pageSize)?$pageSize=15:$pageSize=intval(I("post.pageSize"));
        empty($page)?$pageIndex=1:$pageIndex=intval(I("post.page"));
        
        $where=array(
            "userID"=> $this->user['uid'],
            "isOn"=>1 
        );
        
        $order=array(
            "isDefault"=>"desc",
            "addressID"=>"desc"  
        );
        
        $addressList=D("UserAddress")
        ->where($where)
        ->order($order)
        ->page($pageIndex,$pageSize)
        ->select();
        
        if(!$addressList) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"139"));
        $this->_returnJson(array("result"=>1,"info"=>$addressList));
    }
    
    /**
     *  用户地址列表
     */
    public function getDefaultAddress(){
        $address=D("UserAddress")->where(array("userID"=>$this->user['uid'],"isDefault"=>1,"isOn"=>1))->find();
        if (!$address) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"140"));
        $this->_returnJson(array("result"=>1,"info"=>$address));
    }
    
    /**
     *  用户地址列表操作
     */
    public function addressToDo(){
        $data=array(
            "action"=>I("post.action")  
        );
        
        if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
        
        if($data['action']=="add"){
            $data['userID']=$this->user['uid'];
            $data['province']=I("post.province");
            $data['city']=I("post.city");
            $data['district']=I("post.district");
            $data['address']=I("post.address");
            $data['phone']=I("post.phone");
            $data['consignee']=I("post.consignee");
            $data['zcode']=I("post.zcode");
            $data['addTime']=time();
            if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
            
            //检测是否已经有默认地址
            $isDefault=D("UserAddress")->where(array("userID"=>$this->user['uid'],"isDefault"=>1))->find();
            if(!$isDefault) $data['isDefault']=1;
            $action="add";
        }
        elseif($data['action']=="update"){
            $data['addressID']=I("post.addressID");
            $data['province']=I("post.province");
            $data['city']=I("post.city");
            $data['district']=I("post.district");
            $data['address']=I("post.address");
            $data['phone']=I("post.phone");
            $data['consignee']=I("post.consignee");
            $data['zcode']=I("post.zcode");
            $data['updateTime']=time();
            if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
            
            $isAddress=$this->isAddress($data['addressID']);
            if(!$isAddress) $this->_returnJson(array("result"=>0,"info"=>"address is not exist","code"=>"137"));
            $action="save";
        }
        elseif($data['action']=="delete"){
            $data['addressID']=I("post.addressID");
            $isAddress=$this->isAddress($data['addressID']);
            if(!$isAddress) $this->_returnJson(array("result"=>0,"info"=>"address is not exist","code"=>"137"));
            $data['isOn']=0;
            $action="save";
        }
        elseif($data['action']=="setDefault"){
            $data['addressID']=I("post.addressID");
            $isAddress=$this->isAddress($data['addressID']);
            if(!$isAddress) $this->_returnJson(array("result"=>0,"info"=>"address is not exist","code"=>"137"));
            D("UserAddress")->where(array("userID"=>$this->user['uid']))->save(array("isDefault"=>0));
            $data['isDefault']=1;
            $action="save";
        }
        else{
            $this->_returnJson(array("result"=>0,"info"=>"action error","code"=>"136"));
        }
        
        unset($data['action']);
        $result=D("UserAddress")->$action($data);
        if (!$result) {
            $this->_returnJson(array("result"=>0,"info"=>"system fail","code"=>138));
        }
        $this->_returnJson(array("result"=>1));
    }
    
    /**
     *  是否存在地址 
     */
    private function isAddress($addressID){
        $isAddress=D("UserAddress")->where(array("userID"=> $this->user['uid'],"isOn"=>1,"addressID"=>$addressID))->find();
        return $isAddress;
    }
    
}